import datetime

from other.cfg import Config
from other.change_format import change_format
from other.status import Status
from server.Mysql import MySQL
from other.sql_montage import sqlMontage


class cfg:
    def __init__(self):
        self.cfg = Config()
        self.st = Status()
        self.db = MySQL(self.cfg.res['mysql']['database'], 'sys_config')
        self.cf = change_format()
        self.sm = sqlMontage()

    # 查询参数
    def get_config_data(self, data):
        result = {'msg': '成功', 'code': 200, 'data': [], 'total': None}
        sqls = "where 1=1 "
        sql = ""
        pages = ''
        if data != {}:
            if data.get('pageNum') is not None and data.get('pageSize') is not None:
                if data['pageNum'] != '' and data['pageSize'] != '':
                    pages = " limit {},{}".format(int(data['pageNum']) * int(data['pageSize']) - int(data['pageSize']),
                                                 int(data['pageSize']))
            if data.get('configName') is not None:
                if data['configName'] != '':
                    sql = sql + " and `config_name` like '%{}%'".format(data['configName'])
            if data.get('configKey') is not None:
                if data['configKey'] != '':
                    sql = sql + " and `config_key`='{}'".format(data['configKey'])
            if data.get('configType') is not None:
                if data['configType'] != '':
                    sql = sql + " and `config_type`='{}'".format(data['configType'])
            if data.get('beginTime') is not None and data.get('endTime') is not None:
                if data['beginTime'] != '' and data['endTime'] != '':
                    sql = (sql + " and ('{}'<=`create_time` and `create_time`<='{}')".
                           format(data['beginTime'], data['endTime']))
        # print('total', sqls + sql)
        total = self.db.get(sqls + sql)
        result['total'] = len(total)
        if sql != "":
            sql = sqls + sql + f'{pages}'
        else:
            sql = sqls + f'{pages}'
        # print(sql)
        res = self.db.get(sql)
        if res != ():
            for r in res:
                for key, value in r.items():
                    if isinstance(value, datetime.datetime):
                        r[key] = value.strftime("%Y-%m-%d %H:%M:%S")
                result['data'].append(r)
        result = self.cf.changes_format(result)
        return result

    def get_config_configKey(self, data):
        result = {'msg': '成功', 'code': 200, 'data': {}}
        sql = f"where `config_key`='{data}'"
        res = self.db.get(sql)
        if res != ():
            for r in res:
                for key, value in r.items():
                    if isinstance(value, datetime.datetime):
                        r[key] = value.strftime("%Y-%m-%d %H:%M:%S")
                result['data'] = r
        result = self.cf.changes_format(result)
        return result

    # 新增参数
    def config_data_add(self, data, userInfo):
        result = {'msg': '成功', 'code': 200}
        times = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        g_sql = f"where `config_key`='{data['configKey']}'"
        g_res = self.db.get(g_sql)
        if g_res != ():
            result['code'] = 400
            result['msg'] = '参数键名重复'
        else:
            data['create_by'] = userInfo['userName']
            data['create_time'] = times
            add_sql = self.sm.add_sql_data(data, 'sys_config')
            self.db.adds(add_sql, 'sys_config')
        return result
    

    # 修改参数
    def config_data_edit(self, data, userInfo):
        result = {'msg': '成功', 'code': 200}
        times = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        g_sql = f"where `config_key`='{data['configKey']}'"
        g_res = self.db.get(g_sql)
        ff = False
        if g_res != ():
            for g in g_res:
                if g['config_id'] == data['configId']:
                    ff = True
                else:
                    result['code'] = 400
                    result['msg'] = '参数键名重复'
        else:
            ff = True
        if ff:
            if 'createTime' in data:
                del data['createTime']
            data['update_by'] = userInfo['userName']
            data['update_time'] = times
            edit_sql = self.sm.edit_sql_data(data, 'sys_config', 'config_id', data['configId'])
            # print('edit_sql', edit_sql)
            self.db.edits(edit_sql, 'sys_config')

    # 删除参数
    def config_data_del(self, data):
        result = {'msg': '成功', 'code': 200}
        times = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        ids = [int(x) for x in data.split(',')]
        for i in ids:
            # 删除
            d_sql = f"delete from `sys_config` where `config_id`={i}"
            self.db.edits(d_sql, 'sys_config')
        return result
